<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->

    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" show-icon> </el-alert>
      <el-row class="opt_mar">
        <el-col>
          选择商品分类 :
          <el-cascader v-model="selectId" :options="roleList" :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name' }" @change="selectIdChange"></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs标签栏 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数区域 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button @click="addInfodialog = true" type="primary" :disabled="btnisdisabled">添加参数</el-button>
          <!-- 动态参数表格区域 -->
          <template>
            <el-table border :data="manyList" style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag @close="deleteItem(scope.row,index)" closable v-for="(item, index) in scope.row.attr_vals" :key="index">{{ item }}</el-tag>

                  <!-- <el-input class="input-new-tag" v-model="manyList[scope.$index].inputValue" ref="tagInput" size="small"> </el-input> -->
                  <el-input ref="tagInput" class="input-new-tag" v-model="arr[scope.$index]" placeholder=""></el-input>
                  <el-button type="primary" class="button-new-tag" size="small" @click="showInput(scope.row, scope.$index)">+ 添加</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="editInfodialogFn(scope.row)" size="mini" type="primary" icon="el-icon-edit">修改</el-button>
                  <el-button @click="removeItem(scope.row.attr_id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <!-- 静态参数区域 -->
          <el-button @click="addInfodialog = true" type="primary" :disabled="btnisdisabled">添加参数</el-button>
          <!-- 静态参数表格区域 -->
          <el-table border :data="onlyList" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                  <el-tag @close="deleteItem(scope.row,index)" closable v-for="(item, index) in scope.row.attr_vals" :key="index">{{ item }}</el-tag>

                  <!-- <el-input class="input-new-tag" v-model="manyList[scope.$index].inputValue" ref="tagInput" size="small"> </el-input> -->
                  <el-input ref="tagInput" class="input-new-tag" v-model="arr[scope.$index]" placeholder=""></el-input>
                  <el-button type="primary" class="button-new-tag" size="small" @click="showInput(scope.row, scope.$index)">+ 添加</el-button>
                </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="editInfodialogFn(scope.row)" size="mini" type="primary" icon="el-icon-edit">修改</el-button>
                <el-button @click="removeItem(scope.row.attr_id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加弹框区域 -->
    <el-dialog @close="clearFormInfo" :title="'添加' + dialogText" :visible.sync="addInfodialog" width="50%">
      <!-- 弹框内容 -->
      <el-form :model="addFormInfo" :rules="addFormInforules" ref="ruleForm">
        <el-form-item :label="dialogText" prop="name">
          <el-input v-model="addFormInfo.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addInfodialog = false">取 消</el-button>
        <el-button type="primary" @click="addFormInfoFn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改弹框区域 -->
    <el-dialog @close="editFormInfoFn" :title="'修改' + dialogText" :visible.sync="editInfodialog" width="50%">
      <!-- 弹框内容 -->
      <el-form :model="editFormInfo" :rules="editFormInforules" ref="editruleForm">
        <el-form-item :label="dialogText" prop="name">
          <el-input v-model="editFormInfo.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editInfodialog = false">取 消</el-button>
        <el-button type="primary" @click="editisOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { editcategorybyidattrid, editcategoryInfo, getCategoriesList, getcategoryListbyId, addOnlyOrManyInfo, getOldOnlyOrManyInfo, deletecategoryInfobyId } from '@/api/index.js'
export default {
  data() {
    return {
      arr: [],
      // //*文本框文本
      inputValue: '',
      //*修改数据的当前项
      currentInfo: {},
      //*弹框是否显示
      editInfodialog: false,
      editFormInforules: {
        name: [{ required: true, message: '请输入参数', trigger: 'blur' }],
      },
      //*修改对话框表单信息
      editFormInfo: {
        name: '',
      },
      //*表单验证规则
      addFormInforules: {
        name: [{ required: true, message: '请输入参数', trigger: 'blur' }],
      },
      //*添加表单信息
      addFormInfo: {
        name: '',
      },
      //*弹框是否弹出
      addInfodialog: false,
      //*菜单选中返回值，三级菜单三个数，数组形式
      selectId: [],
      roleList: [],
      //*选中标签返回值
      activeName: 'many',
      //*动态参数信息
      manyList: [],
      //*静态参数信息
      onlyList: [],
    }
  },
  created() {
    this.getCategoryFn()
  },
  methods: {
    //*单击删除某一项
    async deleteItem(row,index){
        //*删除数组中被单击的索引项
      row.attr_vals.splice(index,1)
      let data = {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' '),
      }
      let { data: res } = await editcategorybyidattrid(this.selectId[2], row.attr_id, data)

      if(res.meta.status != 200) { return this.$message.error('删除参数失败')}
      this.$message.success('删除参数成功')
    },
    //*单击事件添加新参数
    async showInput(row, i) {
      if (this.arr[i].trim() == '') {
        return this.$message.error('请先输入数据')
      }
      row.attr_vals.push(this.arr[i].trim())
      let data = {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' '),
      }
      let { data: res } = await editcategorybyidattrid(this.selectId[2], row.attr_id, data)

      if(res.meta.status != 200) { return this.$message.error('添加参数失败')}
      this.$message.success('添加数据成功')
      this.arr[i] = ''
      this.$refs.tagInput.value = ""
    },

    //*根据id删除参数
    removeItem(attrid) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let { data: res } = await deletecategoryInfobyId(this.selectId[2], attrid)
          if (res.meta.status != 200) {
            return this.$message.error('删除参数失败')
          }
          //*数据回显
          this.getcategoryListbyIdFn()
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //*修改完成
    editisOk() {
      this.$refs.editruleForm.validate(async (valid) => {
        if (valid) {
          let { data: res } = await editcategoryInfo(this.selectId[2], this.currentInfo.attr_id, { attr_name: this.editFormInfo.name, attr_sel: this.activeName })
          console.log(res)
          this.$message.success('修改数据成功')
          this.editInfodialog = false
          this.getcategoryListbyIdFn()
        } else {
          this.$message.error('修改数据失败')
          this.editInfodialog = false
        }
      })
    },
    //*打开修改对话框，并获取当前项
    async editInfodialogFn(Info) {
      this.currentInfo = Info
      let { data: res } = await getOldOnlyOrManyInfo(this.selectId[2], Info.attr_id, { attr_sel: this.activeName })
      if (res.meta.status != 200) {
        return this.$message.error('获取信息失败')
      }
      this.editFormInfo.name = res.data.attr_name
      this.editInfodialog = true
    },
    //*清空表单数据重置表单验证
    editFormInfoFn() {
      this.$refs.editruleForm.resetFields()
    },
    //*清空表单数据，重置表单验证
    clearFormInfo() {
      this.$refs.ruleForm.resetFields()
    },
    //*添加数据方法
    addFormInfoFn() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let { data: res } = await addOnlyOrManyInfo(this.selectId[2], { attr_name: this.addFormInfo.name, attr_sel: this.activeName })
          if (res.meta.status != 201) {
            return this.$message.error('添加数据失败')
          }
          this.getcategoryListbyIdFn()
          this.addInfodialog = false
        } else {
          this.$message.error('请输入数据')
        }
      })
    },
    //*根据三级id和分类参数获取参数列表
    async getcategoryListbyIdFn() {
      if (this.selectId.length == 3) {
        let { data: res } = await getcategoryListbyId(this.selectId[2], this.activeName)
        if (res.meta.status == 200) {
          //*根据类别存储参数列表
          if (this.activeName == 'many') {
            this.manyList = res.data
            this.arr = []
            this.manyList.forEach((item, index) => {
              item.inputValue = ''
              this.arr[index] = ''
              if (item.attr_vals !== '') {
                item.attr_vals = item.attr_vals.split(' ')
              } else {
                item.attr_vals = []
              }
            })
          } else {
            this.onlyList = res.data
            this.arr = []
            this.onlyList.forEach((item,index) => {
              this.arr[index] = ''
              item.inputValue = ''
              if (item.attr_vals !== '') {
                item.attr_vals = item.attr_vals.split(' ')
              } else {
                item.attr_vals = []
              }
            })
          }
        } else {
          this.$message.error('获取数据失败')
        }
      }
    },
    //*tabs标签页被单击时触发
    handleClick() {
      this.getcategoryListbyIdFn()
    },
    //*选择菜单项改变触发
    selectIdChange() {
      //*如果数组长度不为三，就清空选择项
      if (this.selectId.length != 3) {
        this.selectId = []
        this.manyList = []
        this.onlyList = []
      }
      this.getcategoryListbyIdFn()
    },
    async getCategoryFn() {
      let { data: res } = await getCategoriesList({})
      if (res.meta.status != 200) {
        return this.$message.error('获取数据失败')
      }
      this.roleList = res.data
    },
  },
  computed: {
    //*按钮是否可以使用
    btnisdisabled() {
      if (this.selectId.length == 3) {
        return false
      } else {
        return true
      }
    },
    //*静态还是动态文本
    dialogText() {
      if (this.activeName == 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    },
  },
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 12px;
}
.opt_mar {
  margin: 15px 0;
}
.el-table {
  margin-top: 12px;
  font-size: 12px;
}
.el-form-item {
  display: flex;
  .el-input {
    width: 100%;
  }
}
.el-tag {
  margin: 7px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  box-sizing: border-box;
}
</style>
